import { Select } from '@alifd/next';
import { SelectProps } from '@alifd/next/types/select';
import _ from 'lodash';
import React, { useEffect, useState } from 'react';
import * as api from './api';
import { observer } from 'mobx-react-lite';


export interface RegionGroupSelectProps extends SelectProps {
  cityId: string;
}

/**
 * 通用区域分组选择器
 *
 */
export default observer(function RegionGroupSelect({ cityId, ...props }: RegionGroupSelectProps) {
  const [data, setData] = useState<{ items: any[], groups: any[] }>({
    items: [],
    groups: [],
  });

  useEffect(() => {
    (async () => {
      let items: any[] = cityId ? await api.getCityItems(cityId) : [];
      const groupMap = items.filter((item) => (item.extras?.group?.value))
        .map((item) => ({ name: item.extras.group.value, city: cityId, item }))
        .reduce((o, c) => {
          const g = o[c.name] || (o[c.name] = { name: c.name, label: c.name, value: c.name, city: c.city, items: [] });
          g.items.push(c.item);
          return o;
        }, {});
      const groups = _.values(groupMap).sort();

      setData({ items, groups });
    })();
  }, [cityId]);

  return (
    <Select
      dataSource={data.groups}
      {...props}
    />
  )
})
